import { useState } from "react";

import { Modal, Form, Input, InputNumber, AutoComplete, Button } from "antd";

import { CloseOutlined } from "@ant-design/icons";

import styles from "./index.module.scss";
import { req } from "@/common/methods";

const ChangeCount = (props: any) => {
  const [form] = Form.useForm();
  const [submitButtonDisabled, setSubmitButtonDisabled] =
    useState<boolean>(false);
  const [showSuccessDetail, setShowSuccessDetail] = useState<boolean>(false);
  //console.log(props);
  const onFinish = (values: any) => {
    //console.log("finish", values);
    if (!values) {
      Modal.error({
        title: "修改失败",
        content: <>数据无效</>,
      });
      return;
    }
    setSubmitButtonDisabled(true);
    try {
      if (typeof values !== "object" || !values) {
        throw "错误的数据类型" + JSON.stringify(values, null, 2);
        return;
      }
      const query = [
        {
          method: 30,
          goods_id: values.goods_id,
          change_count: values.change_count,
          reason: values.reason,
          remark: "[手动修改][" + values.reason + "]" + (values.remark || ""),
        },
      ];
      req("/api/storage", { data: JSON.stringify(query) }, "post")
        .then((data: any) => {
          Modal.success({
            title: "提交成功",
            content: (
              <>
                已完成对物品"{values.goods_name}"的数量修改，修改前的数量为
                {Number(values.before_count)}，修改值为
                <span
                  style={{
                    color: (() => {
                      if (values.change_count > 0) {
                        return "green";
                      } else if (values.change_count < 0) {
                        return "red";
                      } else {
                        return "black";
                      }
                    })(),
                  }}
                >
                  {(Number(values.change_count) > 0 ? "+" : "-") +
                    values.change_count}
                </span>
                ，请留意库存变化
                <span
                  style={{
                    color: "blue",
                    display: !showSuccessDetail ? "block" : "none",
                    cursor: "pointer",
                  }}
                  onClick={() => {
                    setShowSuccessDetail(true);
                    alert(JSON.stringify(data, null, 2));
                  }}
                >
                  查看服务器端处理详情
                </span>
                <pre
                  style={{
                    backgroundColor: "lightgray",
                    maxWidth: 350,
                    display: showSuccessDetail ? "block" : "none",
                  }}
                >
                  {JSON.stringify(data, null, 2)}
                </pre>
              </>
            ),
            onOk() {
              try {
                props.doClose();
                Modal.destroyAll();
              } catch (e) {
                Modal.error({
                  title: "表格更新失败",
                  content: <>无法完成对数据的更新，请刷新重试！{"" + e}</>,
                });
              }
            },
          });
        })
        .catch((error) => {
          Modal.error({
            title: "提交失败",
            content: <>盘点数据提交失败，{"" + error}</>,
          });
          setSubmitButtonDisabled(false);
        });
    } catch (e) {
      Modal.error({
        title: "数据初始化错误",
        content: <>数据校验出现错误,{"" + e}</>,
        onOk() {
          setSubmitButtonDisabled(false);
        },
        onCancel() {
          setSubmitButtonDisabled(false);
        },
      });
    }
  };
  const onFinishFailed = () => {
    Modal.error({
      title: "无法提交更改",
      content: <>请检查所有的填写是否填写规范</>,
    });
  };
  const [hashForChange, setHashForChange] = useState<number>(0);
  return (
    <>
      <div className={styles.floatclose} onClick={() => Modal.destroyAll()}>
        <CloseOutlined
          style={{ fontSize: "20px" }}
          className={styles["close-icon"]}
        />
      </div>
      <Form
        form={form}
        initialValues={{
          ...props,
          after_count: props.before_count,
          change_count: 0,
        }}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <Form.Item
          name="goods_id"
          label="惟一标识符"
          rules={[{ required: true, message: "惟一标识符不能为空" }]}
        >
          <Input disabled />
        </Form.Item>
        <Form.Item
          name="goods_name"
          label="物品名称"
          rules={[{ required: true, message: "物品名称不能为空" }]}
        >
          <Input disabled />
        </Form.Item>
        <Form.Item
          name="before_count"
          label="账存"
          rules={[{ required: true, message: "账存不能为空" }]}
        >
          <InputNumber disabled />
        </Form.Item>
        <Form.Item
          name="after_count"
          label="实存"
          rules={[
            { required: true, message: "实存不能为空" },
            {
              type: "integer",
              min: 0,
              message: "数量最低为0",
            },
          ]}
        >
          <InputNumber
            onChange={(value) => {
              const fieldsValue = form.getFieldsValue();
              const beforeCount = fieldsValue["before_count"]; //form.getFieldValue("before_count");
              if (typeof value === "number") {
                let changeCount = value - beforeCount;
                if (Number.isNaN(changeCount)) {
                  changeCount = 0;
                }
                form.setFieldsValue({
                  ...fieldsValue,
                  change_count: changeCount,
                });
              }
              setHashForChange(Math.random());
            }}
          />
        </Form.Item>
        <Form.Item
          name="change_count"
          label="损溢"
          required
          key={hashForChange}
          rules={[{ required: true, message: "损溢不能为空" }]}
        >
          <InputNumber
            disabled
            style={{
              backgroundColor: (() => {
                const fieldsValue = form.getFieldsValue();
                // console.log(fieldsValue);
                const changeCount = fieldsValue.change_count;
                // console.log(changeCount);
                if (changeCount < 0) {
                  return "#ffaaaa";
                } else if (changeCount > 0) {
                  return "#aaffaa";
                } else {
                  return "lightgray";
                }
              })(),
            }}
          />
        </Form.Item>
        <Form.Item
          name="reason"
          label="事由"
          rules={[{ required: true, message: "事由不能为空" }]}
        >
          <AutoComplete
            options={[
              {
                value: "调整库存",
              },
              {
                value: "记录出错",
              },
              {
                value: "物品损坏导致亏损",
              },
              {
                value: "日常盘点",
              },
              {
                value: "系统问题",
              },
              {
                value: "其他问题",
              },
            ]}
          />
        </Form.Item>
        <Form.Item name="remark" label="备注">
          <Input />
        </Form.Item>
        <Form.Item className={styles["submit-area"]}>
          <Button
            type="primary"
            htmlType="submit"
            disabled={submitButtonDisabled}
            loading={submitButtonDisabled}
          >
            提交更改
          </Button>
        </Form.Item>
      </Form>
    </>
  );
};

export default ChangeCount;
